package com.ssd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssd.api.couponAndIntegral.dto.PointsRecordDTO;
import com.ssd.entity.PointsRecord;
import com.ssd.entity.PointsRecordTotal;
import com.ssd.entity.dto.request.PointsRecordPage;
import com.ssd.mapper.PointsRecordMapper;
import com.ssd.service.IPointsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssd.viewmodel.Pager;
import io.micrometer.core.instrument.binder.BaseUnits;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 积分记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-21
 */
@Service
public class PointsRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements IPointsRecordService {

    @Resource
    private PointsRecordTotalServiceImpl pointsRecordTotalService;

    @Override
    public Pager<PointsRecord> listRecord(PointsRecordPage pointsRecordPage) {
        //设置分页参数
        Page<PointsRecord> page=new Page<>(pointsRecordPage.getPageNum(),pointsRecordPage.getPageSize());
        //分页查询
        Page<PointsRecord> recordPage = lambdaQuery()
                .eq(PointsRecord::getUserId, pointsRecordPage.getUserId())
                .eq(ObjectUtil.isNotNull(pointsRecordPage.getType()), PointsRecord::getType, pointsRecordPage.getType())
                .orderByDesc(PointsRecord::getCreateTime)
                .page(page);
        //返回分页数据
        if (recordPage == null){
            return Pager.buildEmpty();
        }
        return Pager.build(recordPage);
    }

    /**
     * 新增积分记录
     *
     * @param pointsRecordDTO
     * @return
     */
    @Override
    @Transactional
    public Boolean addRecord(PointsRecordDTO pointsRecordDTO) {
        //1.添加总积分表数据
        boolean update = pointsRecordTotalService.lambdaUpdate()
                .eq(PointsRecordTotal::getUserId, pointsRecordDTO.getUserId())
                .setSql("points = points + " + pointsRecordDTO.getPoints()) // 增加积分
                .update();
        if (!update){
            return false;
        }
        //2.添加积分记录
        PointsRecord bean = BeanUtil.toBean(pointsRecordDTO, PointsRecord.class);
        bean.setId(pointsRecordTotalService.generatorPointsRecordId());
        bean.setType(1);//收入
        boolean save = save(bean);
        return save;
    }

}
